﻿using System;
using System.Collections;
using System.Collections.Generic;
using Microsoft.SharePoint;

namespace DynamicSettings
{
    class PropertyList : IList<Property>
    {
        private List<Property> propertyList = new List<Property>();
        private SPWeb oWeb;
        private string dynamicKey = Constants.DynamicSettingsKey;

        /// <summary>
        /// Initializes a new instance of the <see cref="PropertyList"/> class.
        /// </summary>
        /// <param name="oWeb">The o web.</param>
        public PropertyList(SPWeb oWeb)
        {
            this.oWeb = oWeb;
            string tempString = this.oWeb.GetProperty(dynamicKey) as string;
            if (tempString != "")
            {
                string[] tempStringArray = tempString.Split(';');
                for (int i = 0; i < tempStringArray.Length; i++)
                {
                    this.Add(new Property(tempStringArray[i], this.oWeb.GetProperty(tempStringArray[i])));
                }
            }
        }

        /// <summary>
        /// Indexes the of.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns></returns>
        public int IndexOf(Property item)
        {
            return propertyList.IndexOf(item);
        }

        /// <summary>
        /// Indexes the of.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        public int IndexOf(object key)
        {
            foreach (Property property in this)
            {
                if (property.Key.Equals(key))
                {
                    return propertyList.IndexOf(property);
                }
            }
            return -1;
        }

        /// <summary>
        /// Inserts the specified index.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <param name="item">The item.</param>
        public void Insert(int index, Property item)
        {
            propertyList.Insert(index, item);
        }

        /// <summary>
        /// Removes at.
        /// </summary>
        /// <param name="index">The index.</param>
        public void RemoveAt(int index)
        {
            propertyList.RemoveAt(index);
        }

        /// <summary>
        /// Gets or sets the <see cref="DynamicSettings.Property"/> at the specified index.
        /// </summary>
        public Property this[int index]
        {
            get
            {
                return propertyList[index];
            }
            set
            {
                propertyList[index] = value;
            }
        }

        /// <summary>
        /// Adds the specified item.
        /// </summary>
        /// <param name="item">The item.</param>
        public void Add(Property item)
        {
            if (!this.ContainsKey(item.Key))
            {
                propertyList.Add(item);
            }
            else
            {
                throw new SPDuplicateValuesFoundException(String.Format("Property {0} already exists.", item.Key));
            }
        }

        /// <summary>
        /// Clears this instance.
        /// </summary>
        public void Clear()
        {
            propertyList.Clear();
        }

        /// <summary>
        /// Determines whether [contains] [the specified item].
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns>
        ///   <c>true</c> if [contains] [the specified item]; otherwise, <c>false</c>.
        /// </returns>
        public bool Contains(Property item)
        {
            return propertyList.Contains(item);
        }

        /// <summary>
        /// Determines whether the specified key contains key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns>
        ///   <c>true</c> if the specified key contains key; otherwise, <c>false</c>.
        /// </returns>
        public bool ContainsKey(object key)
        {
            foreach (Property property in this)
            {
                if (property.Key.Equals(key))
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// Copies to.
        /// </summary>
        /// <param name="array">The array.</param>
        /// <param name="arrayIndex">Index of the array.</param>
        public void CopyTo(Property[] array, int arrayIndex)
        {
            propertyList.CopyTo(array, arrayIndex);
        }

        /// <summary>
        /// Gets the count.
        /// </summary>
        public int Count
        {
            get { return propertyList.Count; }
        }

        /// <summary>
        /// Gets a value indicating whether this instance is read only.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this instance is read only; otherwise, <c>false</c>.
        /// </value>
        public bool IsReadOnly
        {
            get { return false; }
        }

        /// <summary>
        /// Removes the specified item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns></returns>
        public bool Remove(Property item)
        {
            this.oWeb.DeleteProperty(item.Key);
            return propertyList.Remove(item);
        }

        /// <summary>
        /// Removes the specified key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        public bool Remove(object key)
        {
            if (this.ContainsKey(key))
            {
                this.oWeb.DeleteProperty(key);
                propertyList.RemoveAt(this.IndexOf(key));
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Gets the enumerator.
        /// </summary>
        /// <returns></returns>
        public IEnumerator<Property> GetEnumerator()
        {
            return propertyList.GetEnumerator();
        }

        /// <summary>
        /// Returns an enumerator that iterates through a collection.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
        /// </returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return propertyList.GetEnumerator();
        }

        /// <summary>
        /// Gets the property keys.
        /// </summary>
        public string PropertyKeys
        {
            get
            {
                Property[] tempProps = propertyList.ToArray();
                string tempString = "";
                for (int i = 0; i < tempProps.Length; i++)
                {
                    if (tempString == "")
                        tempString = tempProps[i].Key.ToString();
                    else
                        tempString += String.Format(";{0}", tempProps[i].Key.ToString());
                }
                return tempString;
            }
        }

        /// <summary>
        /// Updates this instance.
        /// </summary>
        public void Update()
        {
            try
            {
                this.oWeb.SetProperty(dynamicKey, this.PropertyKeys);
                foreach (Property property in this)
                {
                    if (this.oWeb.GetProperty(property.Key) == null)
                    {
                        this.oWeb.AddProperty(property.Key, property.Value);
                    }
                    else
                    {
                        this.oWeb.SetProperty(property.Key, property.Value);
                    }
                }
                this.oWeb.Update();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
